<script setup>

  import {reactive, ref} from "vue";
  import request from "@/utils/request";
  import {ElMessage} from "element-plus";
  import { useUserStore } from "@/stores/user";
  import router from "../router";
  import {setRoutes} from "../router";
  import Vcode from "vue3-puzzle-vcode";

  components: {
    Vcode
  }
  //图片滑块验证码
  const isShow = ref(false)


  // 用户通过了验证
  const success = (msg) => {
    isShow.value = false;
    ElMessage.success("登录成功")
    router.push('/')
  }

  // 用户点击遮罩层，应该关闭模态框
  const close = () => {
    isShow.value = false;
  }
  // 用户验证失败
  const fail = () => {
    localStorage.removeItem('manager')
    console.log('验证失败');
  }


  const loginData = reactive({})

  const state = reactive({
    loginAdmin: {}
  })

  const rules = reactive({
    nickname: [
      {required: true, message: '请输入账号', trigger: 'blur'},
    ],

    password: [
      {required: true, message: '请输入密码', trigger: 'blur'},
      { min: 3, max: 8, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
  })

  const ruleFormRef = ref()

  const login = () => {
    ruleFormRef.value.validate(valid => {
      if(valid){
        request.post('/login',loginData).then(res => {
          if(res.code === '200'){
            isShow.value = true;
            const userStore = useUserStore()
            userStore.setManagerInfo(res.data)
          }else {
            ElMessage.error(res.msg)
          }
        })
      }
    })
  }





</script>

<template>
  <div style="height: 100vh;overflow: hidden;background-color: aliceblue; position: relative" >
    <Vcode :show="isShow" @success="success" @close="close" @fail='fail'></Vcode>
    <div style="width: 400px; margin: 150px auto; background-color: white; border: 1px solid #ddd;padding: 30px; border-radius: 10px">
      <el-form
          ref="ruleFormRef"
          :model="loginData"
          :rules="rules"
          size="large"
          status-icon
      >
        <div style="text-align: center;color: dodgerblue;font-size: 25px;font-weight: bold;margin-bottom: 30px">IM-ADMIN</div>
        <el-form-item  prop="nickname">
          <el-input v-model="loginData.nickname" placeholder="请输入账号" :prefix-icon="User" />
        </el-form-item>

        <el-form-item  prop="password">
          <el-input v-model="loginData.password" show-password="" placeholder="请输入密码" :prefix-icon="Lock" />
        </el-form-item>

        <el-form-item >
          <el-button type="primary" style="width: 100%" @click="login">登 录</el-button>
        </el-form-item>
      </el-form>
    </div>

  </div>
</template>


<style scoped>
.cover {
  width: fit-content;
  background-color: white;
  position: absolute;
  top:50%;
  left:50%;
  transform: translate(-50%, -50%);
  z-index: 1000;
}
</style>
